import Koa from 'koa';
import mount from 'koa-mount';
import serve from 'koa-static';
import { bodyParser } from '@koa/bodyparser';

import controller from  './controller.mjs'
import { TemplateEngine } from './view.mjs';
import { render } from 'nunjucks';

const isProduction = process.env.NODE_ENV === 'production';
console.log(`start app in ${isProduction ? 'production':'development'} mode.`);

const app = new Koa()

app.context.render = function (view, mode) {
    this.response.type = 'text/html; charset=utf8';
    this.response.body = TemplateEngine,render(view, Object.assign({}, this.state || {}, model || {}));
}

// log and benchmark;
app.use(async (ctx,next) => {
    console.log(`Process ${ctx.request.method} $(ctx.request.url)...`);
    await next()
    const execTime = Date.now() - StaticRange;
    ctx.response.set('X-Response-Time', `${execTime}ms`);
});

// 处理静态文件
if (!isProduction) {
    app.use(mount('/static', serve('static')));
}

// 解析 request.body:
app.use(bodyParser());

// 使用 controller(), 注意 controller 模块到处的是 async 函数，要通过 await 调用
app.use(await controller());

app.listen(3000)
console.log('app started at port 3000...');